package com.youth.framework.core;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.MessageDigest;
import java.util.Properties;

public class LicenseManager {
	public static void main(String[] args) {
		if (args == null || args.length > 0) {
			String source = "";
			String target = "";
			for (String arg : args) {
				if (arg.startsWith("source=")) {
					source = arg.substring(7);
				} else if (arg.startsWith("target=")) {
					target = arg.substring(7);
				}
			}
			if ("".equals(source.trim())) {
				System.out.println("source file must be setted!");
			}
			if ("".equals(target.trim())) {
				target = source;
			}
			try {
				gererateLicenseFile(source, target);
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		} else {
			String extract = extract();
			if (extract != null) {
				System.out.println(extract);
			} else {
				System.out.println("extract failed!");
			}
		}
	}
	
	private static void gererateLicenseFile(String source, String target) throws Exception {
		Properties props = new Properties();
		File source_file = new File(source);
		if (source_file.exists()) {
			props.load(new FileInputStream(source_file));
			String extract = extract();
			if (extract != null) {
				StringBuilder comments = new StringBuilder();
				comments.append("This file has genereated by system, Do not modify it by yoursel!").append("\r\n");
				comments.append("  Copyright: 2013 hefei kangli technology all rights reserved");
				
				props.put("product.name", "康丽医药物流管理系统");
				props.put("product.version", "Release 3.0.0,2013.12");
				props.put("product.copyright", "2013 合肥康丽科技有限公司");
				props.put("license.sn", extract);
				
				props.store(new FileOutputStream(new File(target)), comments.toString());
				
				BufferedReader reader = null;
				try {
					reader = new BufferedReader(new InputStreamReader(new FileInputStream(target)));
					String line = null;
					StringBuilder licCnt = new StringBuilder();
					while ((line = reader.readLine()) != null) {
						licCnt.append(line);
					}
					System.out.println(generate(licCnt.toString()));
				} finally {
					if (reader != null) {
						try {
							reader.close();
						} catch (IOException e) {
							// 
						}
					}
				}
			} else {
				System.out.println("gererate failed!");
			}
		}
	}
	
	/**
	 * 从给定的授权文件中提取授权信息
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	static Properties extractLicense(String file) throws Exception {
		Properties result = new Properties();
		File licFile = new File(file);
		if (licFile.exists() && file.endsWith(".license")) {
			BufferedReader reader = null;
			try {
				result.load(new FileInputStream(licFile));

				reader = new BufferedReader(new InputStreamReader(new FileInputStream(licFile)));
				String line = null;
				StringBuilder licCnt = new StringBuilder();
				while ((line = reader.readLine()) != null) {
					licCnt.append(line);
				}
				result.put("MessageDigest", generate(licCnt.toString()));
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException e) {
						// 
					}
				}
			}
		} else {
			System.out.println(" 指定的文件不存在或无效！");
		}
		return result;
	}
	
	/**
	 * 从给定的授权文件中提取授权信息
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	static Properties extractLicense(URL url) throws Exception {
		Properties result = new Properties();
		if (url != null) {
			BufferedReader reader = null;
			try {
				result.load(url.openStream());

				reader = new BufferedReader(new InputStreamReader(url.openStream()));
				String line = null;
				StringBuilder licCnt = new StringBuilder();
				while ((line = reader.readLine()) != null) {
					licCnt.append(line);
				}
				result.put("MessageDigest", generate(licCnt.toString()));
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException e) {
						// 
					}
				}
			}
		} else {
			System.out.println(" 指定的文件不存在或无效！");
		}
		return result;
	}

	static String extract() {
		String cachet = null;
		try {
			String os_name = System.getProperty("os.name").toLowerCase();
			if (os_name.startsWith("windows")) {
				cachet = extractForWindows();
			} else if (os_name.startsWith("linux")) {
				cachet = extractForLinux();
			}
			if (cachet != null) {
				cachet = generate(cachet);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cachet;
	}

	private static String generate(String input) throws Exception {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		md5.update(input.getBytes());
		byte[] digest = md5.digest();
		StringBuilder buffer = new StringBuilder();
		char hexes[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };// 用来将字节转换成16进制表示的字符
		for (byte tmp : digest) {
			buffer.append(hexes[tmp >>> 4 & 0xf]);
			buffer.append(hexes[tmp & 0xf]);
		}
		return buffer.toString().toUpperCase();
	}

	private static String extractForWindows() throws IOException {
		StringBuilder info_builder = new StringBuilder("DISKDRIVE:");

		Process process = Runtime.getRuntime().exec("wmic diskdrive get signature");
		process.getOutputStream().close();
		BufferedReader reader = null;
		BufferedReader error = null;
		try {
			reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
			String line;
			int route = 0;
			while (route < 10 && (line = reader.readLine()) != null) {
				info_builder.append("\t").append(line);
			}
			try {
				System.out.println("Process exitValue: " + process.waitFor());
			} catch (InterruptedException e) {
			} 
		} finally {
			if (reader != null) {
				reader.close();
			}
			if (error != null) {
				error.close();
			}
		}

		return info_builder.toString();
	}

	private static String extractForLinux() throws IOException {
		StringBuilder info_builder = new StringBuilder("DISKDRIVE:");

		Process process = Runtime.getRuntime().exec("fdisk -l");
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line;
			String dev = null;
			while ((line = reader.readLine()) != null) {
				if (line.contains("/dev/sda")) {
					dev = "/dev/sda";
					break;
				} else if (line.contains("/dev/hda")) {
					dev = "/dev/hda";
					break;
				}
			}
			reader.close();
			if (dev != null) {
				process = Runtime.getRuntime().exec("hdparm -i " + dev);
				reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
				while ((line = reader.readLine()) != null) {
					if (line.contains("SerialNo")) {
						int index = line.indexOf("SerialNo");
						info_builder.append("\t").append(line.substring(index));
						break;
					}
				}
			}
		} finally {
			if (reader != null) {
				reader.close();
			}
		}

		return info_builder.toString();
	}
}
